package com.ningju.procurement.common.mybatis.pager;

import java.lang.reflect.Field;

public class ReflectUtils {
	
	/**
	 * 获得对象指定字段
	 * @param obj
	 * @param fieldName
	 * @return
	 */
	public static Field getField(Class<?> clazz, String fieldName) {
		Field field = null;
		try {
			field = clazz.getDeclaredField(fieldName);
			if(!field.isAccessible()) {
				field.setAccessible(true);
			}
		} catch (NoSuchFieldException | SecurityException e) {
			e.printStackTrace();
		}
		
		return field;
	}

	/**
	 * 获得对象指定字段的值
	 * @param obj
	 * @param fieldName
	 * @return
	 */
	public static Object getFieldValue(Object obj, String fieldName) {
		Field field = getField(obj.getClass(), fieldName);
		Object value = null;
		try {
			value = field.get(obj);
		} catch (IllegalArgumentException | IllegalAccessException e) {
			e.printStackTrace();
		}
		
		return value;
	}
	
	public static Object getFieldValue(Class<?> clazz, Object obj, String fieldName) {
		Field field = getField(clazz, fieldName);
		Object value = null;
		try {
			value = field.get(obj);
		} catch (IllegalArgumentException | IllegalAccessException e) {
			e.printStackTrace();
		}
		
		return value;
	}
	
	/**
	 * 设置对象指定字段的值
	 * @param obj
	 * @param fieldName
	 * @return
	 */
	public static void setFieldValue(Object obj, String fieldName, Object value) {
		Field field = getField(obj.getClass(), fieldName);
		try {
			field.set(obj, value);
		} catch (IllegalArgumentException | IllegalAccessException e) {
			e.printStackTrace();
		}
	}
	
}